package com.service.totalauth.service.impl;

import com.service.config.utils.IdUtil;
import com.service.config.utils.ModelMapperUtil;
import com.service.config.utils.RedisUtil;
import com.service.config.utils.Result;
import com.service.totalauth.dao.CompanyInfoDao;
import com.service.totalauth.dto.UserDto;
import com.service.totalauth.entity.CompanyInfo;
import com.service.totalauth.entity.ProgrammeApiBind;
import com.service.totalauth.service.CompanyInfoService;
import com.service.totalauth.service.ProgrammeApiBindService;
import com.service.totalauth.vo.AddQyCorpInfoDto;
import com.service.totalauth.vo.FindQyCorpInfoVo;
import com.service.totalauth.vo.UpdateQyCorpInfoDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.service.config.constant.Constant.PARAMETER_NOT_FOUND;
import static com.service.config.constant.Constant.parameterNotFound;
import static com.service.config.utils.CharUtil.getCharAndNumr;

/**
 * 配置信息表(CompanyInfo)表服务实现类
 *
 * @author makejava
 * @since 2021-12-03 09:38:47
 */
@Service("companyInfoService")
public class CompanyInfoServiceImpl implements CompanyInfoService {
    @Resource
    private CompanyInfoDao companyInfoDao;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ProgrammeApiBindService programmeApiBindService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public CompanyInfo queryById(String id) {
        return this.companyInfoDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<CompanyInfo> queryAllByLimit(int offset, int limit) {
        return this.companyInfoDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param companyInfo 实例对象
     * @return 实例对象
     */
    @Override
    public CompanyInfo insert(CompanyInfo companyInfo) {
        this.companyInfoDao.insert(companyInfo);
        return companyInfo;
    }

    /**
     * 修改数据
     *
     * @param companyInfo 实例对象
     * @return 实例对象
     */
    @Override
    public CompanyInfo update(CompanyInfo companyInfo) {
        this.companyInfoDao.update(companyInfo);
        return this.queryById(companyInfo.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.companyInfoDao.deleteById(id) > 0;
    }

    @Override
    public Result addQyCorpInfo(AddQyCorpInfoDto addQyCorpInfoDto, UserDto userDto) {
        CompanyInfo qyCorpInfo = ModelMapperUtil.strictMap(addQyCorpInfoDto, CompanyInfo.class);
        qyCorpInfo.setCpAddTime(new Date());
        qyCorpInfo.setId(IdUtil.getStringId());
        qyCorpInfo.setcStatus(true);
        qyCorpInfo.setSecret(addQyCorpInfoDto.getAppSecret());
        qyCorpInfo.setQywxUrl(addQyCorpInfoDto.getSchemeUrl());
        qyCorpInfo.setManageId(userDto.getId());
        qyCorpInfo.setCpAdder(userDto.getUsername());
        qyCorpInfo.setCpUpdater(userDto.getUsername());
        qyCorpInfo.setCpUpdateTime(new Date());
        qyCorpInfo.setCpAddTime(new Date());
        qyCorpInfo.setUrlNumber(verGetCharAndNumber(16));
        int insert = companyInfoDao.insert(qyCorpInfo);
        if (insert > 0) {
            return Result.ok();
        }
        return Result.failure("新增失败，请检查");
    }

    @Override
    @Transactional
    public Result deleteQyCorpInfo(String userId, String qyCorpInfoId) {
        CompanyInfo companyInfo = new CompanyInfo();
        companyInfo.setId(qyCorpInfoId);
        companyInfo.setManageId(userId);
        companyInfo.setcStatus(false);
        companyInfoDao.update(companyInfo);
        return Result.ok();
    }

    @Override
    @Transactional
    public Result updateQyCorpInfo(UpdateQyCorpInfoDto updateQyCorpInfoDto) {
        CompanyInfo companyInfo = ModelMapperUtil.strictMap(updateQyCorpInfoDto, CompanyInfo.class);
        if (updateQyCorpInfoDto.getCStatus()==null)
        {
            companyInfo.setcStatus(true);
        }
        companyInfo.setQywxUrl(updateQyCorpInfoDto.getSchemeUrl());
        companyInfo.setSecret(updateQyCorpInfoDto.getAppSecret());
        companyInfoDao.update(companyInfo);
        return Result.ok();
    }

    /**
     * 刷新密钥
     * @param companyInfoId
     * @return
     */
    @Override
    @Transactional
    public Result freshQyCorpInfo(String companyInfoId) {
        CompanyInfo companyInfo = new CompanyInfo();
        companyInfo.setId(companyInfoId);
        companyInfo.setUrlNumber(verGetCharAndNumber(16));
        int update = companyInfoDao.update(companyInfo);
        ProgrammeApiBind qyProgrammeApiBind = new ProgrammeApiBind();
        qyProgrammeApiBind.setCompanyInfoId(companyInfoId);
        List<ProgrammeApiBind> programmeApiBindList = programmeApiBindService.queryAll(qyProgrammeApiBind);
        if (programmeApiBindList != null) {
            programmeApiBindList.forEach(qyProgrammeApiBind1 -> {
                String onlyUrl = qyProgrammeApiBind1.getOnlyUrl();
                String[] split = onlyUrl.split("&number=");
                onlyUrl = split[0].concat("&number=").concat(companyInfo.getUrlNumber());
                qyProgrammeApiBind1.setOnlyUrl(onlyUrl);
            });
            programmeApiBindService.insertBatch(programmeApiBindList);
            if (update > 0) {
                return Result.ok();
            }
            return Result.failure("修改失败，请检查");
        }
        return Result.ok();
    }

    @Override
    public Result queryByUserId(String userId,Integer type) {
        if (type == null) {
            return Result.failure(PARAMETER_NOT_FOUND,parameterNotFound);
        }
        CompanyInfo companyInfo = new CompanyInfo();
        companyInfo.setManageId(userId);
        companyInfo.setcStatus(true);
        companyInfo.setType(type);
        List<CompanyInfo> companyInfos = companyInfoDao.queryAll(companyInfo);
        List<FindQyCorpInfoVo> findQyCorpInfoVos = new ArrayList<>();
        if (companyInfos.size() > 0) {
            companyInfos.forEach(companyInfo1 -> {
                FindQyCorpInfoVo findQyCorpInfoVo = ModelMapperUtil.strictMap(companyInfo1, FindQyCorpInfoVo.class);
                findQyCorpInfoVo.setAppSecret(companyInfo1.getSecret());
                findQyCorpInfoVo.setSchemeUrl(companyInfo1.getQywxUrl());
                findQyCorpInfoVos.add(findQyCorpInfoVo);
            });
            return Result.ok().setData(findQyCorpInfoVos);
        }
        return Result.ok();
    }
    private String verGetCharAndNumber(int i) {
        CompanyInfo qyCorpInfo = new CompanyInfo();
        qyCorpInfo.setUrlNumber(getCharAndNumr(i));
        List<CompanyInfo> qyCorpInfoList = companyInfoDao.queryAll(qyCorpInfo);
        if (qyCorpInfoList.size() > 0) {
            verGetCharAndNumber(i);
        }
        return qyCorpInfo.getUrlNumber();
    }
    @Override
    public List<CompanyInfo> queryAll(CompanyInfo qyCorpInfo) {
        return companyInfoDao.queryAll(qyCorpInfo);
    }

    @Override
    public CompanyInfo queryByNumber(String number) {
        return companyInfoDao.queryByNumber(number);
    }

    /**
     * 获取微信小程序已绑定的企业微信和未绑定的企业微信
     * @param WechatId
     * @param userId
     * @param type
     * @return
     */
    @Override
    public Result getBindInfo(String WechatId,String userId, Integer type) {
        CompanyInfo companyInfo = new CompanyInfo();
        companyInfo.setManageId(userId);
        companyInfo.setcStatus(true);
        List<CompanyInfo> companyInfoList = companyInfoDao.queryAll(companyInfo);
        if (companyInfoList != null && companyInfoList.size() > 0 ) {
            List<CompanyInfo> collect = companyInfoList.stream().filter(companyInfo1 -> companyInfo1.getType().equals(type)).collect(Collectors.toList());
            List<CompanyInfo> collect1 = companyInfoList.stream().filter(companyInfo1 -> companyInfo1.getType() == 4 && !companyInfo1.getId().equals(WechatId)).collect(Collectors.toList());
            List<FindQyCorpInfoVo> findQyCorpInfoVos = ModelMapperUtil.strictMapList(collect, FindQyCorpInfoVo.class);
            collect1.forEach(companyInfo1 -> {
                if (companyInfo1.getCompanyInfoId() != null && !"".equals(companyInfo1.getCompanyInfoId())) {
                    List<FindQyCorpInfoVo> collect2 = findQyCorpInfoVos.stream().filter(findQyCorpInfoVo ->
                            findQyCorpInfoVo.getId().equals(companyInfo1.getCompanyInfoId())).collect(Collectors.toList());
                    if (collect2.size() > 0) {
                        findQyCorpInfoVos.removeAll(collect2);
                    }
                }
            });
            List<CompanyInfo> collect2 = companyInfoList.stream().filter(companyInfo1 -> companyInfo1.getId().equals(WechatId)).collect(Collectors.toList());
            if (collect2.size() > 0) {
                CompanyInfo companyInfo1 = collect2.stream().findFirst().get();
                if (companyInfo1.getCompanyInfoId() == null || "".equals(companyInfo1.getCompanyInfoId())) {
                    findQyCorpInfoVos.forEach(findQyCorpInfoVo -> findQyCorpInfoVo.setBindStatus(false));
                    return Result.ok().setData(findQyCorpInfoVos);
                }
                findQyCorpInfoVos.forEach(findQyCorpInfoVo -> {
                    if (findQyCorpInfoVo.getId().equals(companyInfo1.getCompanyInfoId())){
                        findQyCorpInfoVo.setBindStatus(true);
                    }else {
                        findQyCorpInfoVo.setBindStatus(false);
                    }
                });
                return Result.ok().setData(findQyCorpInfoVos);
            }
        }
        return Result.failure(PARAMETER_NOT_FOUND,parameterNotFound);
    }
}
